import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:game_wiki_app/app/utils/storage_service.dart';
import 'package:get/get.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'app/routes/app_pages.dart';
import 'app/config/app_branding.dart';
import 'app/data/services/remote_config_service.dart';
import 'app/modules/app_settings/controllers/app_settings_controller.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  // 初始化依赖注入
  await _initDependencies();

  // 设置系统UI样式
  SystemChrome.setSystemUIOverlayStyle(
    const SystemUiOverlayStyle(
      statusBarColor: Colors.transparent,
      statusBarIconBrightness: Brightness.dark,
      statusBarBrightness: Brightness.light,
      systemNavigationBarColor: Colors.white,
      systemNavigationBarIconBrightness: Brightness.dark,
    ),
  );

  // 设置首选方向为竖屏
  await SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
    DeviceOrientation.portraitDown,
  ]);

  runApp(const GameWikiApp());
}

// 初始化依赖注入
Future<void> _initDependencies() async {
  // 初始化存储服务
  final storageService = await StorageService.getInstance();
  Get.put(storageService, permanent: true);
  
  // 初始化远程配置服务
  Get.put(RemoteConfigService(), permanent: true);
  
  // 初始化应用设置控制器
  Get.put(AppSettingsController(), permanent: true);
  
  print('Dependencies initialized successfully');
}

class GameWikiApp extends StatelessWidget {
  const GameWikiApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ScreenUtilInit(
      designSize: const Size(375, 850), // iPhone X设计尺寸
      minTextAdapt: true,
      splitScreenMode: true,
      builder: (context, child) {
        return GetMaterialApp(
          title: AppBranding.appName,
          debugShowCheckedModeBanner: false,

          // 主题配置
          theme: AppBranding.getLightTheme(),
          darkTheme: AppBranding.getDarkTheme(),
          themeMode: ThemeMode.system,

          // 路由配置
          initialRoute: AppPages.INITIAL,
          getPages: AppPages.routes,

          // 国际化配置
          locale: const Locale('zh', 'CN'),
          fallbackLocale: const Locale('zh', 'CN'),

          // 默认过渡动画
          defaultTransition: Transition.cupertino,
          transitionDuration: const Duration(milliseconds: 300),

          // 错误处理
          builder: (context, widget) {
            // 处理文字缩放
            return MediaQuery(
              data: MediaQuery.of(context).copyWith(textScaler: const TextScaler.linear(1.0)),
              child: widget!,
            );
          },

          // 未知路由处理
          unknownRoute: GetPage(
            name: '/notfound',
            page: () => const NotFoundPage(),
          ),
        );
      },
    );
  }
}

// 404页面
class NotFoundPage extends StatelessWidget {
  const NotFoundPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('页面未找到'),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () => Get.offAllNamed(AppPages.INITIAL),
        ),
      ),
      body: Center(
        child: Padding(
          padding: EdgeInsets.all(32.w),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(
                Icons.error_outline,
                size: 64.r,
                color: Colors.grey[400],
              ),
              SizedBox(height: 24.h),
              Text(
                '页面未找到',
                style: TextStyle(
                  fontSize: 24.sp,
                  fontWeight: FontWeight.w600,
                  color: const Color(0xFF333333),
                ),
              ),
              SizedBox(height: 12.h),
              Text(
                '您访问的页面不存在或已被移除',
                style: TextStyle(
                  fontSize: 16.sp,
                  color: const Color(0xFF666666),
                ),
                textAlign: TextAlign.center,
              ),
              SizedBox(height: 32.h),
              ElevatedButton(
                onPressed: () => Get.offAllNamed(AppPages.INITIAL),
                child: const Text('返回首页'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
